package cn.lyq.card.ui.course

import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseFg
import cn.lyq.card.data.model.CourseTypeInfo
import cn.lyq.card.data.src.Status
import cn.lyq.card.utils.bindViewPager
import cn.lyq.card.utils.setSimpleData
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.fg_course.*
import kotlinx.android.synthetic.main.layout_tab_normal.*
import kotlinx.android.synthetic.main.layout_title.*


class CourseFg : BaseFg() {

    private val mModel by lazy {
        getVMActivity(CourseVM::class.java)
    }
    private val mFragments = mutableListOf<BaseFg>()
    private val mTitles = mutableListOf<String>()
    private val mAdapter by lazy {
        MyPagerAdapter(childFragmentManager)
    }

    override fun getLayoutId(): Int {
        return R.layout.fg_course
    }

    override fun initView(view: View) {
        super.initView(view)
        tvTitleSplit.visibility = View.GONE
        imgBack.visibility = View.GONE
        tvTitle.setText(R.string.app_name)
    }

    override fun initObserver() {
        super.initObserver()

        mModel.getType().observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.SUCCESS -> loadTypeSuccess(it.requireData())
                Status.ERROR -> {
                    dismissLoading()
                    ToastUtils.showShort(it.message.getMsg())
                }
            }
        })
    }

    private fun loadTypeSuccess(data: MutableList<CourseTypeInfo>) {
        mModel.mTypeList.clear()
        mTitles.clear()
        mFragments.clear()
        mModel.mTypeList.addAll(data)
        mModel.mTypeList.withIndex().forEach {
            mTitles.add(it.value.title ?: "")
            mFragments.add(CourseSubFg.newInstance(it.index))
        }
        viewPager.adapter = mAdapter
        if (data.size > 4) {
            slidingTab.setViewPager(viewPager, mTitles.toTypedArray())
            tabLayout.visibility = View.GONE
        } else {
            tabLayout.setSimpleData(mTitles.toTypedArray())
            tabLayout.bindViewPager(viewPager)
            slidingTab.visibility = View.GONE
        }
    }

    inner class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getCount(): Int {
            return mModel.mTypeList.size
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return mTitles[position]
        }

        override fun getItem(position: Int): Fragment {
            return mFragments[position]
        }
    }
}